<template>
  <div class="jsa-create">
    <div class="page-container">
      <div class="page-header">
        <h2>JSA创建</h2>
        <div class="header-actions">
          <el-button @click="goBack">
            <el-icon><ArrowLeft /></el-icon>
            返回
          </el-button>
          <el-button type="primary" @click="saveDraft" :loading="saving">
            <el-icon><Document /></el-icon>
            保存草稿
          </el-button>
          <el-button type="success" @click="submitJSA" :loading="submitting">
            <el-icon><Check /></el-icon>
            提交JSA
          </el-button>
        </div>
      </div>
      
      <el-form
        :model="jsaForm"
        :rules="jsaRules"
        ref="jsaFormRef"
        label-width="120px"
      >
        <!-- JSA工作单基本信息 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>JSA工作单</span>
            </div>
          </template>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="分析单位" prop="analysisUnit">
                <el-input v-model="jsaForm.analysisUnit" placeholder="请输入分析单位" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="任务描述" prop="jobDescription">
                <el-input v-model="jsaForm.jobDescription" placeholder="请输入任务描述" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="编号" prop="jsaNumber">
                <el-input v-model="jsaForm.jsaNumber" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="工作位置" prop="workPosition">
                <el-input v-model="jsaForm.workPosition" placeholder="请输入工作位置" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作时间段" prop="workDateDuration">
                <el-date-picker
                  v-model="jsaForm.workDateDuration"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工作负责人" prop="personInCharge">
                <el-select
                  v-model="jsaForm.personInCharge"
                  placeholder="请选择工作负责人"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="person in personnelOptions"
                    :key="person.id"
                    :label="`${person.name} (${person.department})`"
                    :value="person.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="权威认可" prop="areaApproval">
                <el-select
                  v-model="jsaForm.areaApproval"
                  placeholder="请选择权威认可人员"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="person in personnelOptions"
                    :key="person.id"
                    :label="`${person.name} (${person.department})`"
                    :value="person.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="案例分享" prop="caseSharing">
                <el-input v-model="jsaForm.caseSharing" placeholder="请输入案例分享" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        
        <!-- JSA分析表 -->
        <el-card class="form-card">
          <template #header>
            <div class="card-header">
              <span>JSA分析表</span>
              <div class="header-actions">
                <el-button type="primary" size="small" @click="addFromTemplate">
                  <el-icon><Plus /></el-icon>
                  从模板添加
                </el-button>
                <el-button 
                  v-if="!isAnalysisEditMode" 
                  type="success" 
                  size="small" 
                  @click="enterAnalysisEditMode"
                >
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button 
                  v-if="isAnalysisEditMode" 
                  type="info" 
                  size="small" 
                  @click="exitAnalysisEditMode"
                >
                  <el-icon><View /></el-icon>
                  预览
                </el-button>
              </div>
            </div>
          </template>
          
          <!-- 预览模式 -->
          <div v-if="!isAnalysisEditMode">
            <JSATemplateTable 
              v-if="analysisTemplateData" 
              :template="analysisTemplateData" 
            />
            <el-empty 
              v-else 
              description="暂无分析数据，请从模板添加或点击编辑按钮手动创建"
              :image-size="120"
            >
              <template #image>
                <el-icon size="60" color="#c0c4cc"><Document /></el-icon>
              </template>
            </el-empty>
          </div>
          
          <!-- 编辑模式 -->
          <el-card v-if="isAnalysisEditMode" class="form-section" shadow="never">
            <template #header>
              <div class="section-title">
                <el-icon><List /></el-icon>
                <span>JSA分析表</span>
              </div>
              </template>
            <JSATemplateTableForm v-model="jsaAnalysisData" />
          </el-card>
        </el-card>
        
        <!-- 措施落实责任人 -->
        <el-card class="form-card">
          <template #header>
            <span>措施落实责任人</span>
          </template>
          
          <div v-if="jsaAnalysisData.workSteps && jsaAnalysisData.workSteps.length > 0">
            <div 
              v-for="(step, stepIndex) in jsaAnalysisData.workSteps" 
              :key="stepIndex"
              class="step-responsible-item"
            >
              <div class="step-info">
                <div class="step-number">{{ stepIndex + 1 }}</div>
                <div class="step-name">{{ step.stepName || '未命名步骤' }}</div>
              </div>
              <div class="responsible-selector">
                <el-select
                  v-model="step.responsiblePersons"
                  multiple
                  placeholder="选择措施落实责任人"
                  style="width: 100%"
                  filterable
                >
                  <el-option
                    v-for="person in personnelOptions"
                    :key="person.id"
                    :label="`${person.name} (${person.department})`"
                    :value="person.id"
                  />
                </el-select>
              </div>
            </div>
          </div>
          
          <el-empty 
            v-else 
            description="请先添加工作步骤"
            :image-size="80"
          />
        </el-card>
        
        <!-- 分析人员 -->
        <el-card class="form-card">
          <template #header>
            <span>分析人员</span>
          </template>
          
          <el-form-item label="指定分析人员" prop="analyzers">
            <el-select
              v-model="jsaForm.analyzers"
              multiple
              placeholder="请选择分析人员"
              style="width: 100%"
            >
              <el-option
                v-for="person in personnelOptions"
                :key="person.id"
                :label="`${person.name} (${person.department})`"
                :value="person.id"
              />
            </el-select>
          </el-form-item>
          
          <div class="selected-analyzers">
            <h4>已选择的分析人员</h4>
            <div class="analyzer-list">
              <el-tag
                v-for="analyzer in selectedAnalyzers"
                :key="analyzer.id"
                closable
                @close="removeAnalyzer(analyzer.id)"
                style="margin-right: 8px; margin-bottom: 8px"
              >
                {{ analyzer.name }} ({{ analyzer.department }})
              </el-tag>
            </div>
          </div>
        </el-card>
        
        <!-- 确认要求 -->
        <el-card class="form-card">
          <template #header>
            <span>确认要求</span>
          </template>
          
          <el-form-item label="需要确认的人员" prop="confirmers">
            <el-checkbox-group v-model="jsaForm.confirmers">
              <el-checkbox value="analyzers">分析人员</el-checkbox>
              <el-checkbox value="responsible_persons">措施责任人</el-checkbox>
              <el-checkbox value="safety_officer">安全员</el-checkbox>
              <el-checkbox value="supervisor">主管</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="确认截止时间" prop="confirmDeadline">
            <el-date-picker
              v-model="jsaForm.confirmDeadline"
              type="datetime"
              placeholder="选择确认截止时间"
              style="width: 100%"
            />
          </el-form-item>
        </el-card>
      </el-form>
    </div>
    
    <!-- 模板选择对话框 -->
    <TemplateSelectDialog
      v-model="templateDialogVisible"
      :work-type="jsaForm.workType"
      @confirm="handleTemplateSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { ArrowLeft, Document, Check, Plus, Delete, User, Calendar, Clock, Warning, List, Edit, View } from '@element-plus/icons-vue'
import TemplateSelectDialog from './components/TemplateSelectDialog.vue'
import JSATemplateTableForm from './components/JSATemplateTableForm.vue'
import JSATemplateTable from './components/JSATemplateTable.vue'
import type { JSATemplateForm, JSATemplate } from '@/types'

const router = useRouter()


interface JSAForm {
  jsaNumber: string
  analysisUnit: string
  jobDescription: string
  workPosition: string
  workDateDuration: [string, string] | null
  personInCharge: string
  personsAnalyzedJob: string[]
  areaApproval: string
  caseSharing: string
  analyzers: string[]
  confirmers: string[]
  confirmDeadline: string
}

const jsaFormRef = ref<FormInstance>()
const saving = ref(false)
const submitting = ref(false)
const templateDialogVisible = ref(false)
const isAnalysisEditMode = ref(false)

// JSA分析数据，使用与模板相同的格式
const jsaAnalysisData = ref<JSATemplateForm>({
  name: '',
  jobType: '',
  workSteps: [],
  hazards: [],
  controlMeasures: [],
  workStepHazards: [],
  hazardControls: []
})

// 分析模板数据，用于预览模式显示
const analysisTemplateData = computed<JSATemplate | undefined>(() => {
  if (!jsaAnalysisData.value.workSteps.length) return undefined
  
  // 将JSATemplateForm转换为JSATemplate格式用于预览
  return {
    id: 0,
    name: jsaAnalysisData.value.name || 'JSA分析表',
    jobType: jsaAnalysisData.value.jobType || '',
    workSteps: jsaAnalysisData.value.workSteps.map((step, index) => ({
      id: index + 1,
      stepName: step.stepName,
      sequence: index + 1
    })),
    hazards: jsaAnalysisData.value.hazards.map((hazard, index) => ({
      id: index + 1,
      hazardName: hazard.hazardName
    })),
    controlMeasures: jsaAnalysisData.value.controlMeasures.map((measure, index) => ({
      id: index + 1,
      measureName: measure.measureName
    })),
    workStepHazards: jsaAnalysisData.value.workStepHazards.map((relation, index) => ({
      id: index + 1,
      workStepId: relation.workStepSequence,
      hazardId: jsaAnalysisData.value.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
      workStep: {
        id: relation.workStepSequence,
        stepName: jsaAnalysisData.value.workSteps[relation.workStepSequence - 1]?.stepName || '',
        sequence: relation.workStepSequence
      },
      hazard: {
        id: jsaAnalysisData.value.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
        hazardName: relation.hazardName
      }
    })),
    hazardControls: jsaAnalysisData.value.hazardControls.map((relation, index) => ({
      id: index + 1,
      hazardId: jsaAnalysisData.value.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
      controlMeasureId: jsaAnalysisData.value.controlMeasures.findIndex(m => m.measureName === relation.controlMeasureName) + 1,
      hazard: {
        id: jsaAnalysisData.value.hazards.findIndex(h => h.hazardName === relation.hazardName) + 1,
        hazardName: relation.hazardName
      },
      controlMeasure: {
        id: jsaAnalysisData.value.controlMeasures.findIndex(m => m.measureName === relation.controlMeasureName) + 1,
        measureName: relation.controlMeasureName
      }
    })),
    isActive: true,
    createTime: new Date().toLocaleString('zh-CN'),
    updateTime: new Date().toLocaleString('zh-CN'),
    creator: '当前用户'
  }
})

const jsaForm = reactive<JSAForm>({
  jsaNumber: '',
  analysisUnit: '',
  jobDescription: '',
  workPosition: '',
  workDateDuration: null,
  personInCharge: '',
  personsAnalyzedJob: [],
  areaApproval: '',
  caseSharing: '',
  analyzers: [],
  confirmers: ['analyzers', 'responsible_persons'],
  confirmDeadline: ''
})

const jsaRules: FormRules = {
  analysisUnit: [
    { required: true, message: '请输入分析单位', trigger: 'blur' }
  ],
  jobDescription: [
    { required: true, message: '请输入任务描述', trigger: 'blur' }
  ],
  workPosition: [
    { required: true, message: '请输入工作位置', trigger: 'blur' }
  ],
  workDateDuration: [
    { required: true, message: '请选择工作日期/时间段', trigger: 'change' }
  ],
  personInCharge: [
    { required: true, message: '请选择工作负责人', trigger: 'change' }
  ],
  personsAnalyzedJob: [
    { required: true, message: '请选择参加分析的人员', trigger: 'change' }
  ],
  analyzers: [
    { required: true, message: '请选择分析人员', trigger: 'change' }
  ],
  confirmers: [
    { required: true, message: '请选择需要确认的人员', trigger: 'change' }
  ],
  confirmDeadline: [
    { required: true, message: '请选择确认截止时间', trigger: 'change' }
  ]
}


// 人员选项
const personnelOptions = ref([
  { id: '1', name: '张三', department: '维修部' },
  { id: '2', name: '李四', department: '维修部' },
  { id: '3', name: '王五', department: '安全部' },
  { id: '4', name: '赵六', department: '生产部' }
])

// 已选择的分析人员
const selectedAnalyzers = computed(() => {
  return personnelOptions.value.filter(person => 
    jsaForm.analyzers.includes(person.id)
  )
})

// 生成JSA编号
const generateJSANumber = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  return `${year}-WELLTECH-TG-EM-${random}`
}



// 从模板添加
const addFromTemplate = () => {
  templateDialogVisible.value = true
}

// 处理模板选择
const handleTemplateSelect = (template: any) => {
  // 直接将模板数据复制到JSA分析数据中
  jsaAnalysisData.value = {
    name: template.name,
    jobType: template.jobType,
    workSteps: template.workSteps.map((step: any) => ({
      stepName: step.stepName
    })),
    hazards: template.hazards.map((hazard: any) => ({
      hazardName: hazard.hazardName
    })),
    controlMeasures: template.controlMeasures.map((measure: any) => ({
      measureName: measure.measureName
    })),
    workStepHazards: template.workStepHazards.map((relation: any) => ({
      workStepSequence: relation.workStep?.sequence || 0,
      hazardName: relation.hazard?.hazardName || ''
    })),
    hazardControls: template.hazardControls.map((relation: any) => ({
      hazardName: relation.hazard?.hazardName || '',
      controlMeasureName: relation.controlMeasure?.measureName || ''
    }))
  }
  
  // 从模板加载后，默认进入预览模式
  isAnalysisEditMode.value = false
  
  ElMessage.success(`已从模板"${template.name}"加载分析数据`)
}

// 进入分析表编辑模式
const enterAnalysisEditMode = () => {
  isAnalysisEditMode.value = true
}

// 退出分析表编辑模式
const exitAnalysisEditMode = () => {
  isAnalysisEditMode.value = false
}

// 移除分析人员
const removeAnalyzer = (id: string) => {
  jsaForm.analyzers = jsaForm.analyzers.filter(analyzerId => analyzerId !== id)
}


// 保存草稿
const saveDraft = async () => {
  try {
    saving.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('草稿保存成功')
  } catch (error: any) {
    ElMessage.error(error.message || '保存失败')
  } finally {
    saving.value = false
  }
}

// 提交JSA
const submitJSA = async () => {
  if (!jsaFormRef.value) return
  
  try {
    await jsaFormRef.value.validate()
    
    // 验证分析数据
    if (!jsaAnalysisData.value.workSteps.length) {
      ElMessage.error('请从模板添加或手动创建至少一个工作步骤')
      return
    }
    
    const hasEmptySteps = jsaAnalysisData.value.workSteps.some(step => 
      !step.stepName.trim()
    )
    
    if (hasEmptySteps) {
      ElMessage.error('请完善所有工作步骤的信息')
      return
    }
    
    submitting.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('JSA提交成功')
    router.push('/jsa/list')
  } catch (error: any) {
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 返回
const goBack = () => {
  router.push('/jsa/list')
}

onMounted(() => {
  jsaForm.jsaNumber = generateJSANumber()
})
</script>

<style lang="scss" scoped>
.jsa-create {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .form-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 8px;
      }
    }
    
    .form-section {
      margin-bottom: 20px;
      
      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
        
        .el-button {
          margin-left: auto;
        }
      }
    }
  }
  
  .selected-analyzers {
    margin-top: 20px;
    
    h4 {
      color: #333;
      margin-bottom: 12px;
    }
    
    .analyzer-list {
      min-height: 40px;
      padding: 12px;
      border: 1px solid #e4e7ed;
      border-radius: 4px;
      background: #f8f9fa;
    }
  }
  
  // JSA工作单样式
  .field-label {
    font-size: 12px;
    color: #666;
    margin-bottom: 4px;
    font-weight: 500;
  }
  
  .el-form-item__label {
    font-weight: 600;
    color: #333;
  }
  
  // 措施落实责任人样式
  .step-responsible-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 16px;
    background: #fafbfc;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .step-info {
      display: flex;
      align-items: center;
      min-width: 200px;
      margin-right: 20px;
      
      .step-number {
        display: inline-flex;
        align-items: center;
        justify-content: center;
        width: 24px;
        height: 24px;
        background: #409eff;
        color: white;
        border-radius: 50%;
        font-size: 12px;
        font-weight: 600;
        margin-right: 12px;
      }
      
      .step-name {
        font-weight: 500;
        color: #303133;
        flex: 1;
      }
    }
    
    .responsible-selector {
      flex: 1;
    }
  }
}
</style>

